//
//  ConsumerListController.m
//  XiaoMiao
//
//  Created by kinglian_iOS_000 on 2018/1/22.
//  Copyright © 2018年 smallyou. All rights reserved.
//

//controller
#import "ConsumerListController.h"
#import "XMAlbumController.h"
#import "XMPersonInfoController.h"
#import "ProjectSeletedController.h"
#import "AddressProvinceCityController.h"
#import "XMCameraTimeAndAngleViewController.h"
#import "XMNewPersonInfoViewController.h"

//view
#import "ConsumerListCell.h"
#import "ConsumerListHeadView.h"
#import "ConsumerListSectionView.h"
#import "BRPickerView.h"
#import "XMFilterProjectPickerView.h"

//model
#import "ConsumerSectionModel.h"
#import "ConsumerModel.h"
#import "ConsumerFilterModel.h"
#import "ProjectPickerModel.h"
#import "ProjectSeletedModel.h"
#import "BRAddressModel.h"





@interface ConsumerListController () <UITableViewDelegate, UITableViewDataSource, ConsumerListCellDelegate, ConsumerListHeadViewDelegate, KLTableViewPlaceHolderProtocol>

@property (strong, nonatomic) UITableView *tableView;
/** <#属性#> */
@property (nonatomic, strong) UILabel *headTitleLabel;
/** <#属性#> */
@property (nonatomic, strong) ConsumerListHeadView *filterHeaderView;
/** <#属性#> */
@property (nonatomic, copy) NSArray <ConsumerSectionModel *>*listArray;
/** view的高度 */
@property (nonatomic, assign) CGFloat viewHeight;
/** 是否是查询类型 */
@property (nonatomic, assign) BOOL isSearchType;
/** <#属性#> */
@property (nonatomic, copy) NSString *key;
/** <#属性#> */
@property (nonatomic, assign) ConsumerListVCType vcType;
/** <#属性#> */
@property (nonatomic, strong) ConsumerFilterModel *consumerFilterModel;
/** 筛选时间数据 */
@property (nonatomic, strong) NSArray *cateDataSource;
/** 筛选二级三级数据 */
@property (nonatomic, strong) NSArray *subCateDataSource;
/** 筛选选择 */
@property (nonatomic, strong) NSArray *filterSelectArr;


@end

@implementation ConsumerListController

- (instancetype)initWithViewHeight:(CGFloat)viewHeight isSearchType:(BOOL)isSearchType vcType:(ConsumerListVCType)vcType {
    if (self = [super init]) {
        self.viewHeight = viewHeight;
        self.isSearchType = isSearchType;
        self.vcType = vcType;
    }
    
    return self;
}


- (instancetype)initWithKey:(NSString *)key isSearchType:(BOOL)isSearchType vcType:(ConsumerListVCType)vcType {
    if (self = [super init]) {
        self.key = key;
        self.isSearchType = isSearchType;
        self.vcType = vcType;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.viewHeight != 0) {
        self.view.frame = CGRectMake(0, 0, kScreenWidth, self.viewHeight);
    }
    [self setupNav];
    
    [self setupUI];
    
    [self request_load];
    
    [self request_filterProjectData];
    
    [AppNotificationHelpper addObserver:self selector:@selector(updateConsumerListNotification) name:@"_updateConsumerListNotification_" object:nil];
}

- (void)setupNav {
    if (self.isSearchType) {
        self.title = @"查询";

    } else {
        self.title = @"已有客户";
    }
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem app_createItemImageName:@"ic_common_btn_add_blue" target:self action:@selector(rightBarButtonItemClick)];
    self.navigationItem.rightBarButtonItem.tintColor = kMainBlueColor;
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    dictM[NSForegroundColorAttributeName] = kMainBlueColor;
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:dictM forState:UIControlStateNormal];
}


- (void)setupUI {
    if (![NSString app_isBlankString:self.key]) {
        self.title = @"搜索结果";
    }
    
    // 创建头部视图(这个控件不能用 lazy)
    ConsumerListHeadView *filterHeaderView = [ConsumerListHeadView app_viewFromXib];
    self.filterHeaderView = filterHeaderView;
    filterHeaderView.delegate = self;
    [self.view addSubview:filterHeaderView];

    // 创建 tableView
    [self.view addSubview:self.tableView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
//    self.filterHeaderView.frame = CGRectMake(0, 0, kScreenWidth, [ConsumerListHeadView viewHeight]);
//    self.tableView.frame = CGRectMake(0, [ConsumerListHeadView viewHeight], kScreenWidth, kScreenHeight - 64 - [ConsumerListHeadView viewHeight]);
    
    [self.filterHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self.filterHeaderView.superview);
        make.height.mas_equalTo([ConsumerListHeadView viewHeight]);
    }];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.bottom.right.mas_equalTo(self.filterHeaderView.superview);
        
        make.top.mas_equalTo(self.filterHeaderView.mas_bottom);


//        if (![NSString app_isBlankString:self.key]) {
//            make.top.mas_equalTo(self.view.mas_top);
//        } else {
//            make.top.mas_equalTo(self.filterHeaderView.mas_bottom);
//        }
    }];
}

#pragma mark - Request
- (void)request_loadIsHud:(BOOL)isHud {
    KLProgressHUD *progressHUD = nil;
    if (isHud) {
        progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:kLoadingMsg];
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"age"] = self.consumerFilterModel.age.length>0?self.consumerFilterModel.age:@"";
    param[@"city"] = self.consumerFilterModel.city.length>0?self.consumerFilterModel.city:@"";
    
    NSString * cateId = @"";
    NSString * subCateId = @"";
    NSString * subSubCateId = @"";

    if (self.filterSelectArr.count>0) {
        ProjectSeletedModel * cateModel =self.filterSelectArr[0];
        cateId = cateModel.id;
        ProjectSeletedModel * subCateModel =self.filterSelectArr[1];
        subCateId = subCateModel.id;
        ProjectSeletedModel * subSubCateModel =self.filterSelectArr[2];
        subSubCateId = subSubCateModel.id;
         
    }
    param[@"cateId"] = cateId;
    param[@"subCateId"] = subCateId;
    param[@"subSubCateId"] = subSubCateId;

    param[@"time"] = self.consumerFilterModel.time.length>0?self.consumerFilterModel.time:@"";
    //    }
    param[@"reayName"] = self.key.length>0?self.key:@"";
    

    [AppNetwork getWithUrl:kPhotographAnglesListNameUrl refreshCache:NO params:param success:^(id response) {
        progressHUD.hidden = YES;
        
        self.listArray = [ConsumerSectionModel mj_objectArrayWithKeyValuesArray:response[@"photographUserAngleMapViews"]];
        
        [self.tableView app_reloadData];
        
    } fail:^(AppError *error) {
        progressHUD.hidden = YES;
        [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
    }];
}


- (void)request_load {
    [self request_loadIsHud:YES];
}


- (void)request_filterProjectData {
    MJWeakSelf
  
     [AppNetwork getWithUrl:kV2ProjectSeletedListUrl refreshCache:NO params:nil success:^(id response) {
        
        
        NSArray <ProjectSeletedModel *>*cateModels = [NSArray modelArrayWithClass:[ProjectSeletedModel class] json:response[@"timeCateViews"]];

        
        NSArray <ProjectSeletedModel *>*subCateModels = [NSArray modelArrayWithClass:[ProjectSeletedModel class] json:response[@"cateViews"]];
        
        weakSelf.cateDataSource = cateModels;
        weakSelf.subCateDataSource = subCateModels;

    } fail:^(AppError *error) {
        [weakSelf request_filterProjectData];

    }];
     

}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArray[section].photographUserAngleViews.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ConsumerListCell *cell = [tableView dequeueReusableCellWithIdentifier:[ConsumerListCell cellId]];
    
    cell.delegate = self;
    cell.isSearchType = self.isSearchType;
    cell.consumerModel = self.listArray[indexPath.section].photographUserAngleViews[indexPath.row];
    
    MJWeakSelf
    [cell setAvatarClickBlock:^(ConsumerModel *model) {
        
        XMNewPersonInfoViewController * vc = [[XMNewPersonInfoViewController alloc]init];
        vc.partyId = model.partyId;
        [vc setReloadBlock:^{
            [weakSelf request_loadIsHud:YES];
        }];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    [self.filterHeaderView resignFirstResponder];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [ConsumerListSectionView headerFooterViewHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ConsumerListSectionView *sectionView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[ConsumerListSectionView headerFooterViewId]];
    sectionView.name = self.listArray[section].name;
    
    return sectionView;
}

// 每个分区的页眉
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return self.listArray[section].name;
//}
// 索引目录
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (self.vcType != ConsumerListVCTypeName) {
        return nil;
    }
    
//    return @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
    
    NSMutableArray *titles = [NSMutableArray array];
    for (ConsumerSectionModel *model in self.listArray) {
        [titles addObject:model.name];
    }

    return titles;
}



#pragma mark - ConsumerListCellDelegate
- (void)consumerListCell:(ConsumerListCell *)consumerListCell didTapType:(ConsumerListCellTapType)tapType
{
    switch (tapType) {
        case ConsumerListCellTapTypePhoto:
        {
            //查看图库
            XMAlbumController *vc = [[XMAlbumController alloc] init];
            vc.partyId = consumerListCell.consumerModel.partyId;
            vc.realName = consumerListCell.consumerModel.realName;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case ConsumerListCellTapTypeSelf:
        {
//            ProjectSeletedController *project = [[ProjectSeletedController alloc] initOldWithPartyId:consumerListCell.consumerModel.partyId realName:consumerListCell.consumerModel.realName];
            XMCameraTimeAndAngleViewController * vc = [[XMCameraTimeAndAngleViewController alloc]init];
            vc.partyId = consumerListCell.consumerModel.partyId;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case ConsumerListCellTapTypeInfo:
        {
            XMPersonInfoController *info = [[XMPersonInfoController alloc] initWithOther:consumerListCell.consumerModel.partyId];
            [self.navigationController pushViewController:info animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - ConsumerListHeadViewDelegate
- (void)consumerListHeadView:(ConsumerListHeadView *)consumerListHeadView didHeadButtonType:(ConsumerListHeadButtonType)buttonType {
    WEAKSELF
    switch (buttonType) {
        case ConsumerListHeadButtonTypeTime: {
            [BRDatePickerView showDatePickerWithTitle:nil
                                             dateType:UIDatePickerModeDate defaultSelValue:nil
                                           minDateStr:nil
                                           maxDateStr:nil
                                         isAutoSelect:NO themeColor:nil resultBlock:^(NSString *selectValue)
             {
                 weakSelf.consumerFilterModel.time = selectValue;
 
                 [weakSelf.filterHeaderView setButtonTitle:selectValue buttonType:buttonType isReset:NO];
 
                 [weakSelf request_load];
             } cancelBlock:^(NSString *tag) {
                 if (![NSString app_isBlankString:tag]) {
                     
                     weakSelf.consumerFilterModel.time = nil;
                     
                     [weakSelf.filterHeaderView setButtonTitle:nil buttonType:buttonType isReset:YES];
                     
                     [weakSelf request_load];
                 }
             }];
        }
            break;
            
        case ConsumerListHeadButtonTypeProject: {
            if (self.cateDataSource.count == 0) {
                [self request_filterProjectData];
            }else {
                [XMFilterProjectPickerView showFilterProjectPickerWithCateDataSoure:self.cateDataSource subCateDataSoure:self.subCateDataSource resultBlock:^(NSArray<ProjectSeletedModel *> *selectArr) {
                    ProjectSeletedModel * cateModel = selectArr[0];
                    ProjectSeletedModel * subCateModel = selectArr[1];
                    ProjectSeletedModel * subSubCateModel = selectArr[2];
                    
                        NSString *title = [NSString stringWithFormat:@"%@%@%@", cateModel.name.length>0?cateModel.name:@"", subCateModel.name.length>0?subCateModel.name:@"",subSubCateModel.name.length>0?subSubCateModel.name:@""];

                        [weakSelf.filterHeaderView setButtonTitle:title buttonType:buttonType isReset:NO];
                    weakSelf.filterSelectArr = selectArr;
                        [weakSelf request_load];
                } cancelBlock:^(NSString *tag) {
                    
                    weakSelf.filterSelectArr = [NSArray array];
                    
                    [weakSelf.filterHeaderView setButtonTitle:nil buttonType:buttonType isReset:YES];

                    [weakSelf request_load];
                }];
            }
            
        }
            break;
            
        case ConsumerListHeadButtonTypeAge: {
            [BRStringPickerView showStringPickerWithTitle:nil
                                               dataSource:kAgeArray
                                          defaultSelValue:[NSString stringWithFormat:@"%@后", self.consumerFilterModel.age]
                                             isAutoSelect:NO
                                               themeColor:nil
                                              resultBlock:^(id selectValue) 
            {
                if ([NSString app_isBlankString:weakSelf.consumerFilterModel.age] &&
                    [selectValue isEqualToString:@"(null)后"]) {
                    weakSelf.consumerFilterModel.age = [kAgeArray[0] substringWithRange:NSMakeRange(0, 2)];
                    [weakSelf.filterHeaderView setButtonTitle:kAgeArray[0] buttonType:buttonType isReset:NO];
                }else {
                    weakSelf.consumerFilterModel.age = [selectValue substringWithRange:NSMakeRange(0, 2)];
                    [weakSelf.filterHeaderView setButtonTitle:selectValue buttonType:buttonType isReset:NO];
                }

                [weakSelf request_load];
            } cancelBlock:^(NSString *tag){
                if (![NSString app_isBlankString:tag]) {
                    
                    weakSelf.consumerFilterModel.age = nil;
                    
                    [weakSelf.filterHeaderView setButtonTitle:nil buttonType:buttonType isReset:YES];
                    
                    [weakSelf request_load];
                }
            }];
        }
            break;
            
        case ConsumerListHeadButtonTypeLoction: {
            //
            [weakSelf.filterHeaderView setButtonTitle:nil buttonType:buttonType isReset:YES];
            weakSelf.consumerFilterModel.city = nil;
            [weakSelf request_load];
            
            //
    AddressProvinceCityController *address = [[AddressProvinceCityController alloc] initWithAddressVCType:AddressVCTypeProvince parentId:@"" titleName:@""];
            [self.navigationController pushViewController:address animated:YES];
            
            WEAKSELF
            [address setAddressCompleted:^(NSString *province, NSString *city) {
                weakSelf.consumerFilterModel.province = province;
                weakSelf.consumerFilterModel.city = city;
                
                [weakSelf.filterHeaderView setButtonTitle:[NSString stringWithFormat:@"%@%@", province, city] buttonType:buttonType isReset:NO];
                
                [weakSelf request_load];
            }];
        }
            break;
    }
}

- (void)consumerListHeadView:(ConsumerListHeadView *)consumerListHeadView didStartSearchKey:(NSString *)key {
    [self.view endEditing:YES];
    
    self.key = key;
    [self request_load];
    
//    需求修改
//    ConsumerListController *consumerList = [[ConsumerListController alloc] initWithKey:key isSearchType:self.isSearchType vcType:self.vcType];
//    [self.navigationController pushViewController:consumerList animated:nil];
}

#pragma mark - KLTableViewPlaceHolderProtocol
- (UIView *)makePlaceHolderView {
    KLNoValueView *noValueView = [KLNoValueView noValueView];
    noValueView.userInteractionEnabled = NO;
    return noValueView;
}

#pragma mark - Tool
- (NSString *)getSubCateId {
    
    if ([NSString app_isBlankString:self.consumerFilterModel.cateName] || [NSString app_isBlankString:self.consumerFilterModel.subCateName]) {
        return nil;
    }
    
    
    return nil;
}

#pragma mark - Noti
- (void)updateConsumerListNotification {
    [self request_load];
} 

#pragma mark - Lazy
- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.rowHeight = [ConsumerListCell cellHeight];
        tableView.sectionIndexColor = HEXPColor(0x2c2e30, 1.0);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ConsumerListCell class]) bundle:nil] forCellReuseIdentifier:[ConsumerListCell cellId]];
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass(ConsumerListSectionView.class) bundle:nil] forHeaderFooterViewReuseIdentifier:[ConsumerListSectionView headerFooterViewId]];
        
        _tableView = tableView;
    }
    return _tableView;
}

- (ConsumerFilterModel *)consumerFilterModel {
    if (!_consumerFilterModel) { 
        _consumerFilterModel = [[ConsumerFilterModel alloc] init];
    }
    return _consumerFilterModel;
}

- (NSArray *)cateDataSource {
    if (!_cateDataSource) {
        _cateDataSource = [NSMutableArray array];
    }
    return _cateDataSource;
}

- (NSArray *)subCateDataSource {
    if (!_subCateDataSource) {
        _subCateDataSource = [NSMutableArray array];
    }
    return _subCateDataSource;
}

#pragma mark - Action
- (void)rightBarButtonItemClick {
    XMCameraTimeAndAngleViewController *creat = [[XMCameraTimeAndAngleViewController alloc]init];
    [self.navigationController pushViewController:creat animated:YES];
}


@end
